package main

import (
	"bytes"
	"encoding/csv"
	"fmt"
	httpserver "git.inke.cn/inkelogic/daenerys/http/server"
)

func downcsv(c *httpserver.Context) {
	fmt.Println("123")
	file := "11.csv"
	header := []string{
		"标题11",
		"标题22",
	}

	data := [][]string{}
	data = append(data, []string{"1", "2"})
	data = append(data, []string{"11", "22"})
	c.Response.Writer().Header().Add("Content-type", "application/octet-stream")

	excel(c.Response, file, header, data)

}
func excel(c httpserver.Responser, file string, header []string, data [][]string) {
	bytes := &bytes.Buffer{}
	bytes.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，避免使用Microsoft Excel打开乱码
	writer := csv.NewWriter(bytes)
	//按行写入
	writer.Write(header)
	//for _, v := range data {
	//	writer.Write(v)
	//}
	writer.WriteAll(data)
	//writer.Flush() // 此时才会将缓冲区数据写入
	c.Writer().Header().Add("Content-type", "application/octet-stream")
	c.Writer().Header().Add("Content-Disposition", "attachment;filename="+file)
	c.Writer().Write(bytes.Bytes())
}

/*
func downcsv(c *httpserver.Context) {
	exporter := NewCsvExport("您好")
	head := []string{"1", "2"}

	_ = exporter.Write(head)
	body := [][]string{}
	body = append(body, []string{"11", "22"})
	_ = exporter.WriteAll(body)
	filename := exporter.GetFileName()
	c.Response.Writer().Header().Add("Content-type", "application/octet-stream")
	c.Response.Writer().Header().Add("Content-Disposition", "attachment;filename="+filename)

}

type CsvExporter struct {
	writer   *csv.Writer
	filename string
	file     os.File
}

func NewCsvExport(title string) *CsvExporter {
	filename := "123.csv"
	file, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0777)

	csvWriter := csv.NewWriter(file)

	_, _ = file.WriteString("\xEF\xBB\xBF")

	return &CsvExporter{
		writer:   csvWriter,
		filename: filename,
	}
}

func (e *CsvExporter) WriteAll(content [][]string) error {
	return e.writer.WriteAll(content)
}

func (e *CsvExporter) Write(record []string) error {
	return e.writer.Write(record)
}

func (e *CsvExporter) GetFileName() string {
	e.writer.Flush()
	_ = e.file.Close()
	return e.filename
}
*/